package service;

import mapper.TicketMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.BuyTicket;
import pojo.Ticket;
import pojo.User;
import util.SqlSessionFactoryUtil;

import java.util.List;

public class TicketService {
    private final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();

    public BuyTicket selectOneBuyTicket(BuyTicket buyTicket) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TicketMapper mapper = sqlSession.getMapper(TicketMapper.class);

        List<BuyTicket> buyTickets = mapper.selectOneBuyTicketOfTicketNo(buyTicket.get_ticketNo());

        sqlSession.close();

        if (buyTickets.isEmpty()) return null;
        return buyTickets.get(0);
    }

    public List<Ticket> selectAllTicketsOfUserNo(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TicketMapper mapper = sqlSession.getMapper(TicketMapper.class);

        List<Ticket> tickets = mapper.selectAllTicketsOfUserNo(user.get_userNo());

        sqlSession.close();
        return tickets;
    }

    public long addOneTicket(Ticket ticket) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TicketMapper mapper = sqlSession.getMapper(TicketMapper.class);

        List<Long> ticketNo = mapper.addOneTicket(ticket);

        sqlSession.commit();
        sqlSession.close();

        if (!ticketNo.isEmpty()) return ticketNo.get(0);
        return -1;
    }

    public void addOneBuyTicket(BuyTicket buyTicket) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TicketMapper mapper = sqlSession.getMapper(TicketMapper.class);

        mapper.addOneBuyTicket(buyTicket);

        sqlSession.commit();
        sqlSession.close();
    }
}
